import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import { Button, Message, Dialog, Drawer, List } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useState, useRef } from 'react';
import TauTable from '@/components/TauTable';
import SurchargeForm from './components/SurchargeForm';
import { useStore } from '@/hooks';
import { uniqueId } from 'lodash';
import { column } from './stores/definitions';
import styles from './index.module.scss';


const tableId = uniqueId('tauTable-');

function Surcharge() {
  const [surcharge, setSurcharge] = useState([]);
  const [modal, setModal] = useState([]);
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量
  const surchargeRef = useRef(null);

  const { surchargeStore: store } = useStore();

  useEffect(() => {
    (() => {
      init();
    })();
  }, []);

  // 初始化数据
  const init = async () => {
    await store.get();
    setSurcharge(toJS(store.charges));
  };

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = surcharge.slice(startIndex, endIndex);

  // 点击添加
  const handleOpenAdd = () => {
    surchargeRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleEdit = (result) => {
    surchargeRef.current = result;
    setModal(['edit']);
  };

  /**
   * 删除附加费
   * @param {*} result
   * @param {*} i
   */
  const handleDelete = (result) => {
    const { itemId } = result;
    if (!_.isEmpty(result)) {
      Dialog.confirm({
        content: t`确定要删除该条附加费吗?`,
        onOk: async () => {
          await store.dictDelete(itemId);
          await init();
        },
      });
    }
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  /**
   * 添加费用
   * @param {*} result
   */
  const handleAddSurcharge = async (result, v) => {
    if (!_.isEmpty(result)) {
      try {
        const check = surcharge.find((item) => item.itemId === result.itemId);
        if (check !== undefined) {
          Dialog.confirm({
            content: t`当前承运附加费用已存在,请重新添加`,
          });
          return;
        }
        if (v?.length > 0) {
          // eslint-disable-next-line no-param-reassign
          result.extras.price = {
            title: t`假日附加费`,
            value: JSON.stringify(v),
          };
        }
        const args = {
          ...toJS(result),
          dictId: 'taurusSurcharges',
          name: result.itemId,
        };
        await store.create(args);
        Message.success({ content: t`费用添加成功` });
      } catch (error) {
        Message.error({ content: t`费用添加失败` });
        throw error;
      }
    }
    setModal([]);
    init();
  };

  /**
   * 修改费用
   * @param {*} result
   */
  const handleEditSurcharge = async (result, v) => {
    if (!_.isEmpty(result)) {
      try {
        if (v?.length > 0) {
          // eslint-disable-next-line no-param-reassign
          result.extras.price = {
            title: t`夜间行驶费`,
            value: JSON.stringify(v),
          };
        }
        const args = {
          ...toJS(result),
          dictId: 'taurusSurcharges',
          name: result.itemId,
        };
        await store.update(args);
        Message.success({ content: t`附加费用修政成功` });
      } catch (error) {
        Message.error({ content: t`附加费用修政失败` });
        throw error;
      }
    }
    setModal([]);
    init();
  };

  return (
    <TauPage className={`page-container ${styles.surcharge}`}>
      <TauActionPanel
        className="action-panel"
        actions={[
          {
            name: 'btn-placeChannel',
            title: t`添加附加费`,
            type: 'primary',
            onClick: handleOpenAdd,
          },
        ]}
        keywordSearch={{ enabled: false }}
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="name"
          tableLayout="fixed"
          currentPage={currentPage}
          pageSize={pageSize}
          total={surcharge?.length}
          onFetch={({ page, size }) => {
            setCurrentPage(page);
            size && setPageSize(size);
          }}
          dataSource={currentPageData}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i, currentPage, pageSize) },
            column('itemId', { width: 188 }),
            column('extras.price.value', {
              width: 188,
              cell: (v, _, j) => {
                if (j.itemId === '夜间行驶费' || j.itemId === '假日附加费') {
                  const text = JSON.parse(v || '[]');
                  return (<List
                    size="small"
                    dataSource={text}
                    renderItem={(item) => (
                      <List.Item
                        key={item.id}
                        extra={`费用: ${item.rmb}`}
                      >
                        时间段: {item.time}
                      </List.Item>
                    )}
                  />);
                } else {
                  return <span>{v}</span>;
                }
              },
            }),
            column('extras.selectable.value', { width: 100 }),
            column('description', { width: 188 }),
            column('ts', { width: 100 }),
            {
              title: t`操作`,
              dataIndex: 'channelNumber',
              width: 200,
              cell: (_, i, company) => {
                return (
                  <>
                    <Button text type="primary" onClick={() => handleEdit(company, i)} >{t`编辑`}</Button>
                    <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                    <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(company, i)} >{t`删除`}</Button>
                  </>
                );
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={!!modal[0]}
        title={modal[0] === 'add' ? t`添加承运附加费` : t`修改承运附加费`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <SurchargeForm
          surchargeInfo={surchargeRef.current}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleAddSurcharge : handleEditSurcharge}
        />
      </Drawer>
    </TauPage>

  );
}

export default Surcharge;
